package com.dhj.yygh.receiver;

import com.dhj.yygh.constant.MQConst;
import com.dhj.yygh.model.hosp.Schedule;
import com.dhj.yygh.service.RabbitService;
import com.dhj.yygh.service.ScheduleService;
import com.dhj.yygh.vo.msm.MsmVo;
import com.dhj.yygh.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class HospitalReceiver {
    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitService rabbitService;

    /*
    订单监听 mq
    生成订单后，mq 生产消息，被如下方法监听，执行对应方法中逻辑
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConst.QUEUE_ORDER, durable = "true"),
            exchange = @Exchange(value = MQConst.EXCHANGE_DIRECT_ORDER),
            key = {MQConst.ROUTING_ORDER}
    ))
    public void receiver(Message message, Channel channel, OrderMqVo orderMqVo) throws IOException {
        // 下单或取消预约后，更新预约数
        Schedule schedule = scheduleService.getScheduleById(orderMqVo.getScheduleId());

        // 更新号源信息
        schedule.setReservedNumber(orderMqVo.getReservedNumber());
        schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
        scheduleService.updateSchedule(schedule);
        // 更新号源数据后，生产短信 mq 的消息，短信模块对应的监听器监听到，发送短信
        MsmVo msmVo = orderMqVo.getMsmVo();
        if (null != msmVo) {
            rabbitService.sendMessage(MQConst.EXCHANGE_DIRECT_MSM, MQConst.ROUTING_MSM_ITEM, msmVo);
        }
    }
}